<?php

/**
 * Gère les tags pour les photos
 *
 * @author Cyril Souti
 * @version 1.12
 * @package plugins
 *
 */
class Plugins_PhotosPlugin extends Plugins_StrategyPlugin
{
	const ROUTE_PHOTOS = 'photos';
	const PARAMETRE_PHOTOS = 'photos';
	const PARAMETRE_TAG = 'tag';
	const PARAMETRE_TAG_DEFAULT = 'default';
	const CONTROLLER_PHOTOS_DEFAULT = 'photos';

	/**
	 * (non-PHPdoc)
	 * @see Zend/Controller/Plugin/Zend_Controller_Plugin_Abstract#routeStartup($request)
	 *
	 * Déclare la route pour les photos
	 */
	public function routeStartup(Zend_Controller_Request_Abstract $request)
	{
		$front = Zend_Controller_Front::getInstance();
		$router = $front->getRouter();
		$router->addRoute(self::ROUTE_PHOTOS, new Zend_Controller_Router_Route(':'.Plugins_InternationalisationPlugin::PARAMETRE_LANGAGE.'/'.self::CONTROLLER_PHOTOS_DEFAULT.'/:'.self::PARAMETRE_TAG.'/:action/:module/',array("controller" => self::CONTROLLER_PHOTOS_DEFAULT,"action" => "index","module" => "default",Plugins_InternationalisationPlugin::PARAMETRE_LANGAGE => Plugins_InternationalisationPlugin::PARAMETRE_LANGAGE_DEFAULT,self::PARAMETRE_TAG => self::PARAMETRE_TAG_DEFAULT)));
	}

	/**
	 * (non-PHPdoc)
	 * @see Zend/Controller/Plugin/Zend_Controller_Plugin_Abstract#routeShutdown($request)
	 *
	 * Vérifie l'existence du tag
	 */
	public function routeShutdown(Zend_Controller_Request_Abstract $request)
	{
		$tagName = $this->getPlugin()->getRequest()->getParam(self::PARAMETRE_TAG);
		if (strcasecmp($tagName, self::PARAMETRE_TAG_DEFAULT) != 0 && !self::existsTag($tagName)) {
			Manager::saveException(new Plugins_ExceptionPhotos("Tag unavailable"));
		}
	}

	public function getDbTags() {
		// Récupération de tout les tags
		$tableTag = new Models_Content_Tag();
		return $tableTag->getTagsActifs();
	}

	public function getDbImages($tag) {
		// Tag sélectionné => récupération des images correspondantes au tag
		$tableImageTag = new Models_Content_ImageTag();
		$images = $tableImageTag->getImagesOfTag($tag);

		return $images;
	}

	public function getTags() {
		$photosPlugin = $this;
		return Manager::loadCache("photos_tags", function() use($photosPlugin){
			return $photosPlugin->getDbTags();
		});
	}

	public function getTag($tagName) {
		$tags = $this->getTags();
		foreach ($tags as $tag) {
			if (strcasecmp($tagName, $tag->label) == 0) {
				return $tag;
			}
		}
		return null;
	}

	public function existsTag($tagName) {
		return !is_null($this->getTag($tagName));
	}

	public function getImages($tag) {
		if (strcasecmp($tag, self::PARAMETRE_TAG_DEFAULT) != 0) {
			$keyCachePhotosTags = "photos_tag_".str_replace("-", "_", $tag);
			$photosPlugin = $this;
			return Manager::loadCache($keyCachePhotosTags, function() use($photosPlugin, $tag){
				return $photosPlugin->getDbImages($tag);
			});
		}
		return null;
	}
}